<?php

namespace app\user\controller;

use PHPMailer\SendEmail;
use think\Controller;

class Login extends Controller
{
    //前置方法
    protected $beforeActionList = [
        'checkuser' => ['only' => 'index,reg,login'],//表示只有这些方法使用前置方法。
    ];

    public function _initialize()
    {
        //全站信息
        $this->assign([
            'system' => cache('systemsystem' . cookie('think_var')),
            'online' => cache('online' . cookie('think_var')),
        ]);

    }

    /**
     * 检查用户是否登录
     * 登录跳转
     */
    public function checkuser()
    {
        if (session('User', '', 'User')) {
            $this->redirect('index/index');
        }
    }

    public function index()
    {
        $where['lang'] = cookie('think_var');
        $where['status'] = 1;
        $where['model'] = 'index';

        $carousel = db('carousel')
            ->field('image,title,url')
            ->where($where)
            ->order('sort DESC')
            ->limit(6)
            ->select();
        $this->assign('carousel', $carousel);
        return $this->fetch();
    }

    public function reg()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = $this->validate($data, 'User.add');
            if (true !== $result) {
                // 验证失败 输出错误信息
                return ajax_info($result);
            }

            if (!empty($data['password'])) {
                $data['code'] = time();
                $data['password'] = md5($data['password'] . $data['code']);
            } else {
                unset($data['password']);
            }

            $data['lang'] = cookie('think_var');
            $data['mailcode'] = md5($data['mail'] . $data['name']);
            if (model('user')->allowField(true)->save($data)) {
                $user = model('user')->where('id', model('user')->id)->find();
                session('User', $user, 'User');

                $dd = new SendEmail();

                $html = <<<eor
                欢迎您成为我们{$this->request->domain()}的用户，
<a href="{$this->request->domain()}/user-Login-Verification-mailcode-{$data['mailcode']}" >请点击链接验证用户邮箱！</a>
eor;

                $dd->SendEmail($data['mail'], $this->request->domain(), $html);

                return ajax_info(lang('registration success'), 'y');
            } else {
                return ajax_info(lang('registration failed'));
            }

        }
        return $this->fetch();
    }

    public function login()
    {
        if ($this->request->isPost()) {

            $data = $this->request->post();
            $result = $this->validate($data, 'User.pub');
            if (true !== $result) {
                return ajax_info($result);
            }

            $user = model('User')->get(['name' => $data['name']]);

            if (!$user) {
                return ajax_info(lang('User does not exist'));
            }

            if ($user->password != md5($data['password'] . $user->code)) {
                return ajax_info(lang('Incorrect password'));
            }

            $data = ['last_login_time' => time()];

            model('User')->updatalosttime($data, $user->id);
            session('User', $user, 'User');

            return ajax_info(lang('login successful'), 'y');
        }

        return $this->fetch();
    }

    /**
     * 发送邮箱验证
     */
    public function checkmail()
    {
        if ($this->request->isGet()) {
            $user = model('user')->field('name,mail,mailcode')->where('id', session('User', '', 'User')->id)->find();
            $dd = new SendEmail();
            $html = <<<eor
                    欢迎您成为我们{$this->request->domain()}的用户，
    <a href="{$this->request->domain()}/user-Login-Verification-mailcode-{$user['mailcode']}" >请点击链接验证用户邮箱！</a>
eor;
            $result= $dd->SendEmail($user->mail, $this->request->domain(), $html);

            if($result=='1'){
                return ajaxMsg('','邮件发送成功！打开邮件重新设置密码！');
            }else{
                return ajaxMsg('','邮箱发送失败，请联系管理员！'.$result);
            }

        }
    }


    /**
     * 用户验证邮箱
     */
    public function Verification()
    {
        $mailcode = $this->request->param('mailcode');
        if (!empty($mailcode)) {
            if (model('user')->allowField(['ismail'])->save(['ismail' => '1'], ['mailcode' => $mailcode])) {
                session(null, 'User');
                $this->success('用户邮箱通过验证,重新登陆！', 'user/login/index');
            } else {
                $this->error('邮箱验证错误！', 'user/login/index');
            }
        }
        $this->redirect($this->request->domain());
    }


    /**
     * 重置密码
     */
    public function runcheckpwd()
    {
        if ($this->request->post()) {
            $data = $this->request->param();
            $update['code'] = time();
            $update['password'] = md5($data['password'] . $update['code']);
            $update['mailcode'] = md5($data['name'] . $update['code']);
            $where['name'] = $data['name'];
            $where['mailcode'] = $data['mailcode'];

            $ched = model('User')->where($where)->update($update);

            if (!empty($ched)) {
                return ajax_info('恭喜您，密码修改成功！', 'y');
            }
            return ajax_info('请填写正确的用户和密码！或者连接失效');

        }
        return $this->fetch();
    }

    /**
     * 找回密码页面
     */
    public function checkpwd()
    {
        if ($this->request->post()) {

            $data = $this->request->param();
            if (empty($data['name']) || empty($data['mail'])) {
                return ajax_info('请填写正确的用户或通过验证的邮箱');
            }

//            $result = $this->validate($data, 'User.checkpwd');
//            if (true !== $result) {
//                return ajax_info($result);
//            }

            $mailcode = md5($data['mail'] . $data['name'] . time());
            $where['mail'] = $data['mail'];
            $where['name'] = $data['name'];
            $ched = model('User')->where($where)->update(['mailcode' => $mailcode]);
            if (!empty($ched)) {
                $dd = new SendEmail();
                $html = <<<eor
                欢迎您使用我们的找回密码{$this->request->domain()}，{$mailcode}
<a href="{$this->request->domain()}/user-Login-runcheckpwd-mailcode-{$mailcode}" >请点击链接验证用户邮箱！</a>
eor;
               $result= $dd->SendEmail($data['mail'], $this->request->domain(), $html);

               if($result=='1'){
                   return ajax_info('邮件发送成功！打开邮件重新设置密码！', 'y');
               }else{
                   return ajax_info('邮箱发送失败，请联系管理员！');
               }
            }
            return ajax_info('请填写正确的用户或通过验证的邮箱');

        }
        return $this->fetch();
    }
}
